<template>
  <a-modal
    width="700px"
    :bodyStyle="{ height: '450px', overflow: 'auto' }"
    :visible="isModal"
    @cancel="() => isModal = false"
  >
    <div slot="title" class="arrive_modal_head">
      <a-icon type="file-add" class="arrive_modal_icon"/> <span class="arrive_modal_label">新增送达</span>
    </div>
    <a-form-model ref="arriveInfoAddModalRef" :rules="rules" style="width: 100%" labelAlign="left" :model="arriveForm">
      <a-col :xxl="12" :lg="12" :sm="12">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="送达方式:" prop="sendway">
          <a-select allow-clear placeholder="请选择送达方式" v-model="arriveForm.sendway" style="width:220px" >
            <a-select-option v-for="item in Tp_sendwayList" :value="item.value" :key="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :xxl="12" :lg="12" :sm="12">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="收件人:" prop="recipient">
          <a-select
            allow-clear
            placeholder="请选择收件人"
            v-model="arriveForm.recipient"
            @change="recipientChange"
            style="width:220px"
          >
            <a-select-option v-for="(item, id) in recipientnameOption" :value="item.name" :key="id">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <a-col :xxl="24" :lg="24" :sm="24">
        <a-form-model-item :label-col="{ span: 3 }" :wrapper-col="{ span: 18 }" label="文书材料:" prop="materialName">
          <a-input v-model="arriveForm.materialName" style="width:220px" placeholder="请选择文书材料" disabled />
          <a-button type="primary" class="btn_primary_color" style="margin-left: 20px" @click="onSelectDocument"> 选择 </a-button>
        </a-form-model-item>
      </a-col>
      <a-col :xxl="12" :lg="12" :sm="12">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="联系号码:" prop="phone">
          <a-input v-model="arriveForm.phone" placeholder="请输入联系号码" style="width:220px" />
        </a-form-model-item>
      </a-col>
      <a-col :xxl="12" :lg="12" :sm="12">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="发出时间:" prop="sendtime">
          <a-date-picker
            style="width:220px"
            v-model="arriveForm.sendtime"
            placeholder="请选择发出时间"
            valueFormat="yyyy-MM-DD"
            :allowClear="true"
          />
        </a-form-model-item>
      </a-col>
      <a-col :xxl="24" :lg="24" :sm="24">
        <a-form-model-item :label-col="{ span: 3 }" :wrapper-col="{ span: 18 }" label="邮寄单号:" prop="postcode" v-if="arriveForm.sendway === 6003102">
          <a-input v-model="arriveForm.postcode" placeholder="邮寄单号" style="width:500px" />
        </a-form-model-item>
      </a-col>
      <a-col :xxl="24" :lg="24" :sm="24">
        <a-form-model-item :label-col="{ span: 3 }" :wrapper-col="{ span: 18 }" label="邮寄地址:" prop="address" v-if="arriveForm.sendway === 6003102">
          <a-input v-model="arriveForm.address" placeholder="请输入邮寄地址" style="width:500px" />
        </a-form-model-item>
      </a-col>
    </a-form-model>
    <template slot="footer">
      <div style="display: flex; justify-content: center">
        <a-button class="m-r-8 btn_normal_color" icon="rollback" @click="() => isModal = false">取消</a-button>
        <a-button class="m-r-8 btn_primary_color" type="primary" @click="onSubmit" :loading="loading">
          提交
        </a-button>
      </div>
    </template>

    <ArriveDocument
      ref="arriveDocument"
      @setFileInfo="setFileInfo"
      :applyid="applyid"
      :checkObj="materialList"
    ></ArriveDocument>
  </a-modal>
</template>

<script>
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { Tp_sendwayList } from '@/enumeration/Tp_sendway'
import { nanoid } from 'nanoid'
import { saveNewDetail } from '@/api/arrive/apl_arrive_details'
import { getReviewDetailByApplyid } from '@/api/arrive/apl_arrive_details'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    }
  },
  data () {
    return {
      loading: false, // 按钮显示
      isModal: false, // 模态框显示
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门

      materialList: [], // 材料列表
      personObj: {
        id: undefined, // id
        recordid: undefined, // 送达记录id
        sendtime: undefined, // 送达时间
        address: undefined, // 邮寄地址
        recipient: undefined, // 收件人
        phone: undefined, // 电话
        postcode: undefined, // 邮寄单号
        sendway: undefined, // 邮寄方式
        istarget: undefined // 是否是被申请人
      },
      checkId: undefined, // 选中的材料id
      arriveForm: {
        id: undefined, // id
        applyid: undefined, // 申请id
        acceptcode: undefined, // 案号
        noticeperid: undefined, // 通知人id
        noticeper: undefined, // 通知人名称
        materialList: undefined, // 材料文件
        personList: undefined, // 送达人信息

        // 表单字段
        materialName: undefined, // 材料名称
        sendway: undefined, // 送达方式
        sendtime: undefined, // 送达时间
        address: undefined, // 送达地址
        recipient: undefined, // 送达人
        postcode: undefined, // 邮寄单号
        phone: undefined // 联系电话
      },
      rules: {
        recipient: [{ required: true, message: '请输入收件人', trigger: 'blur' }],
        sendway: [{ required: true, message: '请选择送达方式', trigger: 'change' }],
        sendtime: [{ required: true, message: '请选择发出时间', trigger: 'change' }],
        phone: [{ required: true, validator: this.checkPhone }],
        address: [{ required: true, message: '请输入邮寄地址', trigger: 'change' }],
        postcode: [{ required: true, message: '请输入邮寄单号', trigger: 'change' }],
        materialName: [{ required: true, message: '请选择文书材料', trigger: 'blur' }]
      },
      Tp_sendwayList: Tp_sendwayList,

      recipientnameOption: [],
      // 默认人员信息：
      // 申请人信息
      applicantList: [],
      // 代理人信息
      agentList: [],
      // 被申请人信息
      targetList: [],
      // 第三人信息
      thirdList: []
    }
  },
 async created () {
    // 默认人员信息
    if (!(this.recipientnameOption && this.recipientnameOption.length > 0)) {
      this.getDefaultPersonInfo()
    }
    this.recipientnameOption = this.$store.state.arrive.recipientnameOption
    this.arriveForm.applyid = this.applyid
    this.arriveForm.acceptcode = this.$store.state.arrive.acceptcode
    this.arriveForm.noticeperid = this.currentUser.userId // 记录人
    this.arriveForm.noticeper = this.currentUser.fullname // 记录人
  },
  components: {
    ArriveDocument: () => import('@/views/arrive/ArriveDocument.vue')
  },
  methods: {
    async getDefaultPersonInfo () {
      const res = await getReviewDetailByApplyid(this.applyid)
      if (res.code == 0) {
        const resObj = res.data
        this.recipientnameOption = []
        if (resObj != null && resObj != undefined) {
            // 被申请人信息：
            this.targetList = resObj.targetList
            // 申请人信息
            this.applicantList = resObj.applicantList
            // 代理人信息
            this.agentList = resObj.agentList
            // 第三人信息
            this.thirdList = resObj.thirdList
            // 送达信息
            this.arriveInfo = resObj.arriveInfo

            if (this.applicantList) {
              this.applicantList.forEach((item) => {
                item.label = '申请人-' + item.name
                item.personType = 'applicant'
                this.recipientnameOption.push(item)
              })
            }
            if (this.agentList) {
              this.agentList.forEach((item) => {
                item.label = '代理人-' + item.name
                item.personType = 'agent'
                this.recipientnameOption.push(item)
              })
            }
            if (this.targetList) {
              this.targetList.forEach((item) => {
                item.label = '被申请人-' + item.name
                item.personType = 'target'
                this.recipientnameOption.push(item)
              })
            }
            if (this.thirdList) {
              this.thirdList.forEach((item) => {
                item.label = '第三人-' + item.name
                item.personType = 'third'
                this.recipientnameOption.push(item)
              })
            }
            // 将数据插入到缓存中
            this.$store.commit('SET_RECIPIENTNAME_OPTION', this.recipientnameOption)
          }
      } else {
        this.$message.error('获取默认人员信息失败')
      }
    },
    resetForm () {
      this.personObj = {
        id: undefined, // id
        recordid: undefined, // 送达记录id
        sendtime: undefined, // 送达时间
        address: undefined, // 邮寄地址
        recipient: undefined, // 收件人
        phone: undefined, // 电话
        postcode: undefined, // 邮寄单号
        sendway: undefined, // 邮寄方式
        istarget: undefined // 是否是被申请人
      }
      this.arriveForm = {
        id: undefined, // id
        applyid: undefined, // 申请id
        acceptcode: undefined, // 案号
        noticeperid: undefined, // 通知人id
        noticeper: undefined, // 通知人名称
        materialList: undefined, // 材料文件
        personList: undefined, // 送达人信息

        // 表单字段
        materialName: undefined, // 材料名称
        sendway: undefined, // 送达方式
        sendtime: undefined, // 送达时间
        address: undefined, // 送达地址
        recipient: undefined, // 送达人
        postcode: undefined, // 邮寄单号
        phone: undefined // 联系电话
      }
      this.arriveForm.id = nanoid()
      this.arriveForm.applyid = this.applyid
      this.arriveForm.acceptcode = this.$store.state.arrive.acceptcode
      this.arriveForm.noticeperid = this.currentUser.userId // 记录人
      this.arriveForm.noticeper = this.currentUser.fullname // 记录人
      this.checkId = undefined
    },
    init () {
      this.resetForm()
      this.isModal = true
    },
    onSubmit () {
      if (this.validate()) {
        this.personObj.id = nanoid()
        this.personObj.recordid = this.arriveForm.id
        this.personObj.address = this.arriveForm.address
        this.personObj.recipient = this.arriveForm.recipient
        this.personObj.phone = this.arriveForm.phone
        this.personObj.postcode = this.arriveForm.postcode
        this.personObj.sendway = this.arriveForm.sendway
        this.personObj.sendtime = this.arriveForm.sendtime

        const perosonList = []
        let materialList = []
        perosonList.push(this.personObj)
        materialList = this.materialList
        this.arriveForm.personList = perosonList
        this.arriveForm.materialList = materialList
        this.loading = true
        saveNewDetail(this.arriveForm).then(res => {
          if (res.code == 0) {
            this.$message.success('新增送达信息成功')
            this.isModal = false
            this.$emit('reload')
          } else {
            this.$message.error('新增送达信息失败')
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.$message.warn('请填写完整信息')
      }
    },
    checkPhone (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入联系号码'))
      }
      if (value && !/^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/.test(value)) {
        callback(new Error('请输入正确的联系号码'))
      }
      callback()
    },
    validate () {
      let validateResult = false
      this.$refs.arriveInfoAddModalRef.validate((valid) => {
        validateResult = valid
      })
      return validateResult
    },
    onSelectDocument () {
      this.$refs.arriveDocument.init()
    },
    setFileInfo (infoList) {
      if (infoList && infoList.length > 0) {
        const file = []
        this.materialList = []
        infoList.forEach(info => {
          const mateialObj = {}
          mateialObj.id = nanoid()
          mateialObj.recordid = this.arriveForm.id
          mateialObj.matttype = info.document.mattype // 文书类型
          mateialObj.attachid = info.document.attachid
          mateialObj.materialid = info.document.id
          mateialObj.stage = info.document.stage
          file.push(info.title)
          this.materialList.push(mateialObj)
        })
        this.arriveForm.materialName = file.join(',')
      }
      this.validate()
    },

    recipientChange (val) {
      // 通过对应的值来设置身份证等默认值
      const selectPerson = this.recipientnameOption.filter((item) => item.name == val)[0]
      if (selectPerson) {
        if (selectPerson.personType == 'applicant') {
          this.arriveForm.address = selectPerson.addr
          this.arriveForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        } else if (selectPerson.personType == 'target') {
          this.arriveForm.address = selectPerson.address
          this.arriveForm.phone = selectPerson.phone
          this.personForm.istarget = 3200 // 是
        } else if (selectPerson.personType == 'third') {
          this.arriveForm.address = selectPerson.addr
          this.arriveForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        } else if (selectPerson.personType == 'agent') {
          this.arriveForm.address = selectPerson.addr
          this.arriveForm.phone = selectPerson.tel
          this.personForm.istarget = 3201 // 否
        }
      }
    }

  }
}
</script>

<style lang="scss" scoped>

  .arrive_modal_head {
    display: flex;
    align-items: center;
  }
  .arrive_modal_icon {
    font-size: 20px;
    color: #0073C7;
    font-weight: bold;
    margin-right: 20px;
  }
  .arrive_modal_label {
    font-family: Source Han Sans CN;
    font-weight: bold;
    font-size: 20px !important;
    color: #2C2C2C;
  }

</style>
